//
//  HotelAlbumListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/8/7.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "ZZLayout.h"
#import "CLPlayerView.h"
#import "GKPhotoBrowser.h"

#import "CommonMediaModel.h"

#import "HotelAlbumVideoCell.h"
#import "HotelAlbumPhotoCell.h"
#import "NormalCollectionSectionTitleView.h"

#import "HotelAlbumListViewController.h"

@interface HotelAlbumListViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, ZZLayoutDelegate,HotelAlbumVideoCellDelegate,GKPhotoBrowserDelegate>

@property (weak, nonatomic) IBOutlet UIButton *videoBtn;

@property (weak, nonatomic) IBOutlet UIButton *photoBtn;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionview;

@property (nonatomic, strong) NSMutableArray <CommonMediaModel *>*imgTextList;

@property (nonatomic, strong) NSMutableArray *photoArray;


@property (nonatomic, strong) NSMutableArray <CommonMediaModel *>*videoList;

/**CLplayer*/
@property (nonatomic, weak) CLPlayerView *playerView;
/**记录Cell*/
@property (nonatomic, assign) UICollectionViewCell *cell;

@end

@implementation HotelAlbumListViewController

- (void)dealloc {
    
    [self.playerView pausePlay];
    [self.playerView destroyPlayer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.playerView pausePlay];
    [self.playerView destroyPlayer];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    WEAKSELF
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.videoBtn pp_clipCorners:UIRectCornerAllCorners radius:weakSelf.videoBtn.frame.size.height/2];
        [weakSelf.photoBtn pp_clipCorners:UIRectCornerAllCorners radius:weakSelf.photoBtn.frame.size.height/2];
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self request_Album];
}

- (void)initView {

    self.title = @"酒店相册";

    ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeVertical delegate:self];
    //打开区头悬浮功能(默认关闭)
    layout.sectionHeadersPinToVisibleBounds = NO;

    _collectionview.collectionViewLayout = layout;
    _collectionview.backgroundColor = UIColorHex(0xf1f1f1);
    _collectionview.delegate = self;
    _collectionview.dataSource = self;
    
    [_collectionview registerNib:[UINib nibWithNibName:@"HotelAlbumVideoCell" bundle:nil] forCellWithReuseIdentifier:@"HotelAlbumVideoCellID"];
    
    [_collectionview registerNib:[UINib nibWithNibName:@"HotelAlbumPhotoCell" bundle:nil] forCellWithReuseIdentifier:@"HotelAlbumPhotoCellID"];

    
    [_collectionview registerNib:[UINib nibWithNibName:@"NormalCollectionSectionTitleView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"NormalCollectionSectionTitleView"];
    
    [_collectionview registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];
    

    _collectionview.showsHorizontalScrollIndicator = NO;
    _collectionview.showsVerticalScrollIndicator = NO;

    _collectionview.bounces = YES;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    if (@available(iOS 11.0, *)) {
        _collectionview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}


- (IBAction)videoAction:(id)sender {
    
    if (self.videoList.count > 0) {
        
        UICollectionViewLayoutAttributes *attributes = [self.collectionview layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        CGRect rect = attributes.frame;
        [self.collectionview setContentOffset:CGPointMake(self.collectionview.frame.origin.x, rect.origin.y-50) animated:YES];
    } else {
        
        [SVProgressHUD showErrorWithStatus:@"该商家未上传视频"];
        [SVProgressHUD dismissWithDelay:1];
    }
}

- (IBAction)imageAction:(id)sender {
    
    if (self.imgTextList.count > 0) {
        
        UICollectionViewLayoutAttributes *attributes = [self.collectionview layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
        CGRect rect = attributes.frame;
        [self.collectionview setContentOffset:CGPointMake(self.collectionview.frame.origin.x, rect.origin.y-50) animated:YES];
        
    } else {
        
        [SVProgressHUD showErrorWithStatus:@"该商家未上传相册"];
        [SVProgressHUD dismissWithDelay:1];
    }
}

- (void)showImageWithArray:(NSArray *)imageUrls index:(NSInteger)index {
    NSMutableArray *photos = [NSMutableArray new];
    
    [imageUrls enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GKPhoto *photo = [GKPhoto new];
        photo.url = [NSURL URLWithString:obj];
        [photos addObject:photo];
    }];
    
    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:photos currentIndex:index];
    browser.showStyle = GKPhotoBrowserShowStyleNone;
    browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
    
    browser.delegate  = self;
    [browser showFromVC:self];
}

#pragma mark- 协议方法
//collectionView的协议方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    switch (section) {
        case HotelAlbumSectionType_video:{
            return self.videoList.count;
        } break;
        case HotelAlbumSectionType_image:{
            return self.imgTextList.count;
        } break;
            default:
            break;
    }
    return 0;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头
    if (kind == UICollectionElementKindSectionHeader) {
        NormalCollectionSectionTitleView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"NormalCollectionSectionTitleView" forIndexPath:indexPath];
        
        switch (indexPath.section) {
            case HotelAlbumSectionType_video:{
                headerView.sectionTitleLab.text = @"视频";
            } break;
            case HotelAlbumSectionType_image:{
                headerView.sectionTitleLab.text = @"图片";
            } break;
            default:
                break;
        }
        
        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        reusableView = footerView;
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    switch (indexPath.section) {
        case HotelAlbumSectionType_video:{

        } break;
        case HotelAlbumSectionType_image:{

            if (self.photoArray.count > 0) {
                [self showImageWithArray:self.photoArray index:indexPath.row];
            }
            
        } break;
            default:
            break;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case HotelAlbumSectionType_video:{

            HotelAlbumVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotelAlbumVideoCellID" forIndexPath:indexPath];
            [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:self.videoList[indexPath.row].videoCover] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            cell.delegate = self;

//            cell.HotelAlbumVideoBlock = ^{
//                
//            };
            return cell;
            
        } break;
            case HotelAlbumSectionType_image:{

                HotelAlbumPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotelAlbumPhotoCellID" forIndexPath:indexPath];
                [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:self.imgTextList[indexPath.row].url] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            return cell;
                
            } break;
        default:
            break;
    }
    
    HotelAlbumPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotelAlbumPhotoCellID" forIndexPath:indexPath];
    return cell;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的高

    switch (indexPath.section) {
        case HotelAlbumSectionType_video:{
            return TTScreenWidth*0.5;
        } break;
        case HotelAlbumSectionType_image:{
            return 110;
        } break;
            default:
            break;
    }
    return 200;
}

- (NSInteger)layout:(ZZLayout *)layout columnNumberAtSection:(NSInteger)section {//每个区有几列
    
    switch (section) {
        case HotelAlbumSectionType_video:{
            return 1;
        } break;
        case HotelAlbumSectionType_image:{
            return 2;
        } break;
            default:
            break;
    }
    return 1;
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    
    switch (section) {
        case HotelAlbumSectionType_video:{
            
            if (self.videoList.count > 0) {
                return UIEdgeInsetsMake(15, 15, 15, 15);
            } else {
                return UIEdgeInsetsMake(0, 0, 0, 0);
            }
        } break;
        case HotelAlbumSectionType_image:{
            if (self.imgTextList.count > 0) {
                return UIEdgeInsetsMake(15, 15, 15, 15);
            } else {
                return UIEdgeInsetsMake(0, 0, 0, 0);
            }

        } break;
            default:
            break;
    }
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距

    switch (section) {
        case HotelAlbumSectionType_video:{
            return 10;
        } break;
        case HotelAlbumSectionType_image:{
            return 10;
        } break;
            default:
            break;
    }
    return 0;
}

- (CGFloat)layout:(ZZLayout*)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距

    switch (section) {
        case HotelAlbumSectionType_video:{
            return 10;
        } break;
        case HotelAlbumSectionType_image:{
            return 10;
        } break;
            default:
            break;
    }
    return 0;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度

    switch (section) {
        case HotelAlbumSectionType_video:{
            return CGSizeMake(TTScreenWidth, 50);
        } break;
        case HotelAlbumSectionType_image:{
            return CGSizeMake(TTScreenWidth, 50);
        } break;
            default:
            break;
    }
    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForFooterInSection:(NSInteger)section {//设置区尾的高度
    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGFloat)layout:(ZZLayout*)layout spacingWithLastSectionForSectionAtIndex:(NSInteger)section {//本区区头和上个区区尾的间距
    return 0;
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {//设置不同分区的不同背景颜色
    return [UIColor whiteColor];
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case HotelAlbumSectionType_video:{

            HotelAlbumVideoCell * myCell = (HotelAlbumVideoCell *)cell;
    
            [myCell fillCellWithModel:self.videoList[indexPath.row]];
        } break;
            case HotelAlbumSectionType_image:{
                
            } break;
        default:
            break;
    }
}



- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case HotelAlbumSectionType_video:{
            
            //因为复用，同一个cell可能会走多次
            if ([_cell isEqual:cell]) {
                //区分是否是播放器所在cell,销毁时将指针置空
                [_playerView destroyPlayer];
                _cell = nil;
            }
        } break;
        case HotelAlbumSectionType_image:{
        } break;
        default:
            break;
    }
}


#pragma mark - 点击播放代理
- (void)cl_CellPlayVideoWithCell:(HotelAlbumVideoCell *)cell{
    //记录被点击的Cell
    _cell = cell;
    //销毁播放器
    [_playerView destroyPlayer];
    CLPlayerView *playerView = [[CLPlayerView alloc] initWithFrame:CGRectMake(0, 0, TTScreenWidth - 30, TTScreenWidth*0.5)];
    _playerView = playerView;
    [cell.contentView addSubview:_playerView];
    //视频地址
    _playerView.url = [NSURL URLWithString:cell.model.url];

    [_playerView updateWithConfigure:^(CLPlayerViewConfigure *configure) {
        configure.topToolBarHiddenType = TopToolBarHiddenSmall;
//        config.smallGestureControl = YES;
    }];
    //播放
    [_playerView playVideo];
    //返回按钮点击事件回调
    [_playerView backButton:^(UIButton *button) {
        NSLog(@"返回按钮被点击");
    }];
    //播放完成回调
    [_playerView endPlay:^{
        //销毁播放器
        [self->_playerView destroyPlayer];
        self->_playerView = nil;
        self->_cell = nil;
        NSLog(@"播放完成");
    }];
}

- (NSMutableArray<CommonMediaModel *> *)imgTextList {
    if (!_imgTextList) {
        _imgTextList = @[].mutableCopy;
    }
    return _imgTextList;
}

- (NSMutableArray<CommonMediaModel *> *)videoList {
    if (!_videoList) {
        _videoList = @[].mutableCopy;
    }
    return _videoList;
}

- (void)request_Album {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.storeId forKey:@"bhSellerId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_HotelAlbum];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSArray *resultArray = [data valueForKey:@"data"];

                weakSelf.photoArray = @[].mutableCopy;
                weakSelf.videoList = @[].mutableCopy;
                weakSelf.imgTextList = @[].mutableCopy;

                if ([resultArray isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < resultArray.count; i++) {
                        CommonMediaModel *mediaModel = [CommonMediaModel modelWithDictionary:resultArray[i]];

                        if (mediaModel.type == 1) {
                            [weakSelf.videoList addObject:mediaModel];

                        } else if (mediaModel.type == 2) {
                            
                            if (mediaModel.url.length > 0) {
                                [weakSelf.photoArray addObject:mediaModel.url];
                            }
                            [weakSelf.imgTextList addObject:mediaModel];
                        }
                        
                    }
                }
                
                [weakSelf.videoBtn setTitle:[NSString stringWithFormat:@"视频%lu",(unsigned long)weakSelf.videoList.count] forState:UIControlStateNormal];
                [weakSelf.photoBtn setTitle:[NSString stringWithFormat:@"相册%lu",(unsigned long)weakSelf.imgTextList.count] forState:UIControlStateNormal];

                [weakSelf.collectionview reloadData];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
    }];
    
}

@end
